$(document).ready(function () {
    if ($.browser.opera == true) {

        $('#menu').css('left', '-280px');
        $("#menu").addClass("sideleft-mob");

        $("#menu-link").click(function () {
            if ($("#menu").hasClass("sideleft-mob")) {
                $("#menu").removeClass("sideleft-mob");
                $('#menu').css('left', '0px');
            } else {
                $("#menu").addClass("sideleft-mob");
                $('#menu').css('left', '-280px');
            }

        });
    }

});


//*********************  Select all items checkbox using jQuery  *********************//	
$(document).ready(function () {

    $("#maincheck").click(function () {
        if ($('#maincheck').attr('checked')) {
            $('.mc').attr('checked', true);
        } else {
            $('.mc').attr('checked', false);
        }
    });


});

//*********************  Fancy Box  *********************//
$(document).ready(function () { $('.fancybox').fancybox(); });
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++

!function ($) {

    $(function () {

        // Disable certain links in docs
        $('section [href^=#]').click(function (e) {
            e.preventDefault()
        })

        // make code pretty
        window.prettyPrint && prettyPrint()

        // add-ons
        $('.add-on :checkbox').on('click', function () {
            var $this = $(this)
              , method = $this.attr('checked') ? 'addClass' : 'removeClass'
            $(this).parents('.add-on')[method]('active')
        })

        // position static twipsies for components page
        if ($(".twipsies a").length) {
            $(window).on('load resize', function () {
                $(".twipsies a").each(function () {
                    $(this)
                      .tooltip({
                          placement: $(this).attr('title')
                      , trigger: 'manual'
                      })
                      .tooltip('show')
                })
            })
        }

        // add tipsies to grid for scaffolding
        if ($('#grid-system').length) {
            $('#grid-system').tooltip({
                selector: '.show-grid > div'
              , title: function () { return $(this).width() + 'px' }
            })
        }

        // fix sub nav on scroll
        var $win = $(window)
          , $nav = $('.subnav')
          , navTop = $('.subnav').length && $('.subnav').offset().top - 40
          , isFixed = 0

        processScroll()

        // hack sad times - holdover until rewrite for 2.1
        $nav.on('click', function () {
            if (!isFixed) setTimeout(function () { $win.scrollTop($win.scrollTop() - 47) }, 10)
        })

        $win.on('scroll', processScroll)

        function processScroll() {
            var i, scrollTop = $win.scrollTop()
            if (scrollTop >= navTop && !isFixed) {
                isFixed = 1
                $nav.addClass('subnav-fixed')
            } else if (scrollTop <= navTop && isFixed) {
                isFixed = 0
                $nav.removeClass('subnav-fixed')
            }
        }

        // tooltip demo
        $('.tooltip-bottom').tooltip({
            placement: "bottom",
            selector: "a[data-t=tooltip]"
        })
        $('.tooltip-top').tooltip({
            placement: "top",
            selector: "a[data-t=tooltip]"
        })
        $('.tooltip-left').tooltip({
            placement: "left",
            selector: "a[data-t=tooltip]"
        })
        $('.tooltip-right').tooltip({
            placement: "right",
            selector: "a[data-t=tooltip]"
        })


        $('.popover-top').popover({
            placement: "top"
        })
        $('.popover-bottom').popover({
            placement: "bottom"
        })
        $('.popover-left').popover({
            placement: "left"
        })
        $('.popover-right').popover({
            placement: "right"
        })

        // popover demo
        $("a[data-t=popover]")
          .popover()
          .click(function (e) {

              e.preventDefault()
          })

        // button state demo
        $('#fat-btn')
          .click(function () {
              var btn = $(this)
              btn.button('loading')
              setTimeout(function () {
                  btn.button('reset')
              }, 3000)
          })

        // carousel demo
        $('#myCarousel').carousel()

        // javascript build logic
        var inputsComponent = $("#components.download input")
          , inputsPlugin = $("#plugins.download input")
          , inputsVariables = $("#variables.download input")

        // toggle all plugin checkboxes
        $('#components.download .toggle-all').on('click', function (e) {
            e.preventDefault()
            inputsComponent.attr('checked', !inputsComponent.is(':checked'))
        })

        $('#plugins.download .toggle-all').on('click', function (e) {
            e.preventDefault()
            inputsPlugin.attr('checked', !inputsPlugin.is(':checked'))
        })

        $('#variables.download .toggle-all').on('click', function (e) {
            e.preventDefault()
            inputsVariables.val('')
        })

        // request built javascript
        $('.download-btn').on('click', function () {

            var css = $("#components.download input:checked")
                  .map(function () { return this.value })
                  .toArray()
              , js = $("#plugins.download input:checked")
                  .map(function () { return this.value })
                  .toArray()
              , vars = {}
              , img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png']

            $("#variables.download input")
              .each(function () {
                  $(this).val() && (vars[$(this).prev().text()] = $(this).val())
              })

            $.ajax({
                type: 'POST'
            , url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com'
            , dataType: 'jsonpi'
            , params: {
                js: js
              , css: css
              , vars: vars
              , img: img
            }
            })
        })
    })

    // Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi
    $.ajaxTransport('jsonpi', function (opts, originalOptions, jqXHR) {
        var url = opts.url;

        return {
            send: function (_, completeCallback) {
                var name = 'jQuery_iframe_' + jQuery.now()
                  , iframe, form

                iframe = $('<iframe>')
                  .attr('name', name)
                  .appendTo('head')

                form = $('<form>')
                  .attr('method', opts.type) // GET or POST
                  .attr('action', url)
                  .attr('target', name)

                $.each(opts.params, function (k, v) {

                    $('<input>')
                      .attr('type', 'hidden')
                      .attr('name', k)
                      .attr('value', typeof v == 'string' ? v : JSON.stringify(v))
                      .appendTo(form)
                })

                form.appendTo('body').submit()
            }
        }
    })

}(window.jQuery)
/*jslint unparam: true */
/*global window, document, $ */
$(function () {
    'use strict';

    // Start slideshow button:
    $('#start-slideshow').button().click(function () {
        var options = $(this).data(),
            modal = $(options.target),
            data = modal.data('modal');
        if (data) {
            $.extend(data.options, options);
        } else {
            options = $.extend(modal.data(), options);
        }
        modal.find('.modal-slideshow').find('i')
            .removeClass('icon-play')
            .addClass('icon-pause');
        modal.modal(options);
    });

    // Toggle fullscreen button:
    $('#toggle-fullscreen').button().click(function () {
        var button = $(this),
            root = document.documentElement;
        if (!button.hasClass('active')) {
            $('#modal-gallery').addClass('modal-fullscreen');
            if (root.webkitRequestFullScreen) {
                root.webkitRequestFullScreen(
                    window.Element.ALLOW_KEYBOARD_INPUT
                );
            } else if (root.mozRequestFullScreen) {
                root.mozRequestFullScreen();
            }
        } else {
            $('#modal-gallery').removeClass('modal-fullscreen');
            (document.webkitCancelFullScreen ||
                document.mozCancelFullScreen ||
                $.noop).apply(document);
        }
    });



});



//*******************  UI  *******************//
$(function () {

    // Accordion
    $("#accordion").accordion({ header: "h3" });

    // Tabs
    $('#tabs').tabs();

    // Dialog			
    $('#dialog').dialog({
        autoOpen: false,
        width: 600,
        buttons: {
            "Ok": function () {
                $(this).dialog("close");
            },
            "Cancel": function () {
                $(this).dialog("close");
            }
        }
    });

    // Dialog Link
    $('#dialog_link').click(function () {
        $('#dialog').dialog('open');
        return false;
    });

    // Datepicker
    $('#datepicker').datepicker({
        inline: true
    });
    $('#inline-datepicker').datepicker({
        inline: true
    });

    // Slider
    $("#slider").slider(
        {
            slide: function (event, ui) {
                $("#amount").val("$" + ui.value);
            }
        }
    );

    $("#slider2").slider({
        value: 100,
        min: 0,
        max: 500,
        step: 1,
        slide: function (event, ui) {
            $("#amount").val("$" + ui.value);
        }
    });
    $("#amount").val("$" + $("#slider").slider("value"));
    $("#slider-range").slider({
        range: true,
        min: 0,
        max: 500,
        values: [75, 300],
        slide: function (event, ui) {
            $("#amount2").val("$" + ui.values[0] + " - $" + ui.values[1]);
        }
    });
    $("#amount2").val("$" + $("#slider-range").slider("values", 0) +
        " - $" + $("#slider-range").slider("values", 1));
    // setup graphic EQ
    $("#eq > span").each(function () {
        // read initial values from markup and remove that
        var value = parseInt($(this).text(), 10);
        $(this).empty().slider({
            value: value,
            range: "min",
            animate: true,
            orientation: "vertical"
        });
    });
    $("#slider-range-min").slider({
        range: "min",
        value: 23,
        min: 23,
        max: 500,
        slide: function (event, ui) {
            $("#amount3").val("$" + ui.value);
        }
    });
    $(".demo_slider").slider({
        range: "min",
        value: 321,
        min: 23,
        max: 500,
        slide: function (event, ui) {
            $("#amountasf").val("$" + ui.value);
        }
    });
    $("#amount3").val("$" + $("#slider-range-min").slider("value"));
    $("#slider-range-max").slider({
        range: "max",
        value: 56,
        min: 1,
        max: 350,
        slide: function (event, ui) {
            $("#amount4").val("$" + ui.value);
        }
    });
    $("#amount4").val("$" + $("#slider-range-min").slider("value"));
    // Progressbar
    $("#progressbar").progressbar({
        value: 20
    });

    //hover states on the static widgets
    $('#dialog_link, ul#icons li').hover(
        function () { $(this).addClass('ui-state-hover'); },
        function () { $(this).removeClass('ui-state-hover'); }
    );

});

//*******************  MENU LEFT  *******************//
jQuery.fn.initMenu = function () {
    return this.each(function () {
        var theMenu = $(this).get(0);
        $('.acitem', this).hide();
        $('li.expand > .acitem', this).show();
        $('li.expand > .acitem', this).prev().addClass('active');
        $('li a', this).click(
            function (e) {
                e.stopImmediatePropagation();
                var theElement = $(this).next();
                var parent = this.parentNode.parentNode;
                if ($(parent).hasClass('noaccordion')) {
                    if (theElement[0] === undefined) {
                        window.location.href = this.href;
                    }
                    $(theElement).slideToggle('normal', function () {
                        if ($(this).is(':visible')) {
                            $(this).prev().addClass('active');
                        }
                        else {
                            $(this).prev().removeClass('active');
                        }
                    });
                    return false;
                }
                else {
                    if (theElement.hasClass('acitem') && theElement.is(':visible')) {
                        if ($(parent).hasClass('collapsible')) {
                            $('.acitem:visible', parent).first().slideUp('normal',
                            function () {
                                $(this).prev().removeClass('active');
                            }
                        );
                            return false;
                        }
                        return false;
                    }
                    if (theElement.hasClass('acitem') && !theElement.is(':visible')) {
                        $('.acitem:visible', parent).first().slideUp('normal', function () {
                            $(this).prev().removeClass('active');
                        });
                        theElement.slideDown('normal', function () {
                            $(this).prev().addClass('active');
                        });
                        return false;
                    }
                }
            }
    );
    });
};

$(document).ready(function () { $('.menu').initMenu(); });

//********************* Contact list *********************//	
$(document).ready(function () {
    $('#slider-contact').sliderNav();
});

//*********************  CALENDAR  *********************//			
$(document).ready(function () {
    if ($.browser.opera == true) {
        return;
    }

    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    var h = {};

    if ($(window).width() <= 320) {
        h = {
            left: 'title, prev,next',
            center: '',
            right: 'today,month,agendaWeek,agendaDay'
        };
    } else {
        h = {
            left: 'title',
            center: '',
            right: 'prev,next,today,month,agendaWeek,agendaDay'
        };
    }

    var initDrag = function (el) {
        // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
        // it doesn't need to have a start or end
        var eventObject = {
            title: $.trim(el.text()) // use the element's text as the event title
        };
        // store the Event Object in the DOM element so we can get to it later
        el.data('eventObject', eventObject);
        // make the event draggable using jQuery UI
        el.draggable({
            zIndex: 999,
            revert: true, // will cause the event to go back to its
            revertDuration: 0 //  original position after the drag
        });
    }

    var addEvent = function (title, priority) {
        title = title.length == 0 ? "Untitled Event" : title;
        priority = priority.length == 0 ? "default" : priority;

        var html = $('<div data-class="label label-' + priority + '" class="external-event label label-' + priority + '">' + title + '</div>');
        jQuery('#event_box').append(html);
        initDrag(html);
    }

    $('#external-events div.external-event').each(function () {
        initDrag($(this))
    });

    $('#event_add').click(function () {
        var title = $('#event_title').val();
        var priority = $('#event_priority').val();
        addEvent(title, priority);
    });

    //modify chosen options
    var handleDropdown = function () {
        $('#event_priority_chzn .chzn-search').hide(); //hide search box
        $('#event_priority_chzn_o_1').html('<span class="label label-default">' + $('#event_priority_chzn_o_1').text() + '</span>');
        $('#event_priority_chzn_o_2').html('<span class="label label-success">' + $('#event_priority_chzn_o_2').text() + '</span>');
        $('#event_priority_chzn_o_3').html('<span class="label label-info">' + $('#event_priority_chzn_o_3').text() + '</span>');
        $('#event_priority_chzn_o_4').html('<span class="label label-warning">' + $('#event_priority_chzn_o_4').text() + '</span>');
        $('#event_priority_chzn_o_5').html('<span class="label label-important">' + $('#event_priority_chzn_o_5').text() + '</span>');
    }

    $('#event_priority_chzn').click(handleDropdown);

    //predefined events
    addEvent("My Event 1", "default");
    addEvent("My Event 2", "success");
    addEvent("My Event 3", "info");
    addEvent("My Event 4", "warning");
    addEvent("My Event 5", "important");
    addEvent("My Event 6", "success");
    addEvent("My Event 7", "info");
    addEvent("My Event 8", "warning");
    addEvent("My Event 9", "success");
    addEvent("My Event 10", "default");

    $('#calendar').fullCalendar({
        header: h,
        editable: true,
        droppable: true, // this allows things to be dropped onto the calendar !!!
        drop: function (date, allDay) { // this function is called when something is dropped

            // retrieve the dropped element's stored Event Object
            var originalEventObject = $(this).data('eventObject');
            // we need to copy it, so that multiple events don't have a reference to the same object
            var copiedEventObject = $.extend({}, originalEventObject);

            // assign it the date that was reported
            copiedEventObject.start = date;
            copiedEventObject.allDay = allDay;
            copiedEventObject.className = $(this).attr("data-class");

            // render the event on the calendar
            // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
            $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);

            // is the "remove after drop" checkbox checked?
            if ($('#drop-remove').is(':checked')) {
                // if so, remove the element from the "Draggable Events" list
                $(this).remove();
            }
        },
        events: [{
            title: 'All Day Event',
            start: new Date(y, m, 1),
            className: 'label label-default',
        }, {
            title: 'Long Event',
            start: new Date(y, m, d - 5),
            end: new Date(y, m, d - 2),
            className: 'label label-success',
        }, {
            id: 999,
            title: 'Repeating Event',
            start: new Date(y, m, d - 3, 16, 0),
            allDay: false,
            className: 'label label-default',
        }, {
            id: 999,
            title: 'Repeating Event',
            start: new Date(y, m, d + 4, 16, 0),
            allDay: false,
            className: 'label label-important',
        }, {
            title: 'Meeting',
            start: new Date(y, m, d, 10, 30),
            allDay: false,
            className: 'label label-info',
        }, {
            title: 'Lunch',
            start: new Date(y, m, d, 12, 0),
            end: new Date(y, m, d, 14, 0),
            allDay: false,
            className: 'label label-warning',
        }, {
            title: 'Birthday Party',
            start: new Date(y, m, d + 1, 19, 0),
            end: new Date(y, m, d + 1, 22, 30),
            allDay: false,
            className: 'label label-success',
        }, {
            title: 'Click for Google',
            start: new Date(y, m, 28),
            end: new Date(y, m, 29),
            url: 'http://google.com/',
            className: 'label label-warning',
        }]
    });



});






//********************* Automatic Infinite Carousel (CHAT)  *********************//
$(document).ready(function () {

    // Gallery
    if (jQuery("#gallery").length) {

        // Declare variables
        var totalImages = jQuery("#gallery > li").length,
            imageWidth = jQuery("#gallery > li:first").outerWidth(true),
            totalWidth = imageWidth * totalImages,
            visibleImages = Math.round(jQuery("#gallery-wrap").width() / imageWidth),
            visibleWidth = visibleImages * imageWidth,
            stopPosition = (visibleWidth - totalWidth);

        jQuery("#gallery").width(totalWidth);

        jQuery("#gallery-prev").click(function () {
            if (jQuery("#gallery").position().left < 0 && !jQuery("#gallery").is(":animated")) {
                jQuery("#gallery").animate({ left: "+=" + imageWidth + "px" });
            }
            return false;
        });

        jQuery("#gallery-next").click(function () {
            if (jQuery("#gallery").position().left > stopPosition && !jQuery("#gallery").is(":animated")) {
                jQuery("#gallery").animate({ left: "-=" + imageWidth + "px" });
            }
            return false;
        });
    }

});
/* Placeholder IE */
(function ($) {
    function Placeholder(input) {
        this.input = input;
        if (input.attr('type') == 'password') {
            this.handlePassword();
        }
        // Prevent placeholder values from submitting
        $(input[0].form).submit(function () {
            if (input.hasClass('placeholder') && input[0].value == input.attr('placeholder')) {
                input[0].value = '';
            }
        });
    }
    Placeholder.prototype = {
        show: function (loading) {
            // FF and IE saves values when you refresh the page. If the user refreshes the page with
            // the placeholders showing they will be the default values and the input fields won't be empty.
            if (this.input[0].value === '' || (loading && this.valueIsPlaceholder())) {
                if (this.isPassword) {
                    try {
                        this.input[0].setAttribute('type', 'text');
                    } catch (e) {
                        this.input.before(this.fakePassword.show()).hide();
                    }
                }
                this.input.addClass('placeholder');
                this.input[0].value = this.input.attr('placeholder');
            }
        },
        hide: function () {
            if (this.valueIsPlaceholder() && this.input.hasClass('placeholder')) {
                this.input.removeClass('placeholder');
                this.input[0].value = '';
                if (this.isPassword) {
                    try {
                        this.input[0].setAttribute('type', 'password');
                    } catch (e) { }
                    // Restore focus for Opera and IE
                    this.input.show();
                    this.input[0].focus();
                }
            }
        },
        valueIsPlaceholder: function () {
            return this.input[0].value == this.input.attr('placeholder');
        },
        handlePassword: function () {
            var input = this.input;
            input.attr('realType', 'password');
            this.isPassword = true;
            // IE < 9 doesn't allow changing the type of password inputs
            if ($.browser.msie && input[0].outerHTML) {
                var fakeHTML = $(input[0].outerHTML.replace(/type=(['"])?password\1/gi, 'type=$1text$1'));
                this.fakePassword = fakeHTML.val(input.attr('placeholder')).addClass('placeholder').focus(function () {
                    input.trigger('focus');
                    $(this).hide();
                });
                $(input[0].form).submit(function () {
                    fakeHTML.remove();
                    input.show()
                });
            }
        }
    };
    var NATIVE_SUPPORT = !!("placeholder" in document.createElement("input"));
    $.fn.placeholder = function () {
        return NATIVE_SUPPORT ? this : this.each(function () {
            var input = $(this);
            var placeholder = new Placeholder(input);
            placeholder.show(true);
            input.focus(function () {
                placeholder.hide();
            });
            input.blur(function () {
                placeholder.show(false);
            });

            // On page refresh, IE doesn't re-populate user input
            // until the window.onload event is fired.
            if ($.browser.msie) {
                $(window).load(function () {
                    if (input.val()) {
                        input.removeClass("placeholder");
                    }
                    placeholder.show(true);
                });
                // What's even worse, the text cursor disappears
                // when tabbing between text inputs, here's a fix
                input.focus(function () {
                    if (this.value == "") {
                        var range = this.createTextRange();
                        range.collapse(true);
                        range.moveStart('character', 0);
                        range.select();
                    }
                });
            }
        });
    }
})(jQuery);
jQuery('input[placeholder], textarea[placeholder]').placeholder();

/* Chosen */
$(".chzn-select").chosen();
/* autorisize */
$(document).ready(function () {
    $('textarea.resize-text').autoResize({});
});

/* Auto TAB (Input) */
$(document).ready(function () {
    $('#autotab_example').submit(function () { return false; });
    $('#autotab_example :input').autotab_magic();
    // Number example
    $('#area_code, #number1, #number2').autotab_filter('numeric');
    $('#ssn1, #ssn2, #ssn3').autotab_filter('numeric');
    // Text example
    $('#text1, #text2, #text3').autotab_filter('text');
    // Alpha example
    $('#alpha1, #alpha2, #alpha3, #alpha4, #alpha5').autotab_filter('alpha');
    // Alphanumeric example
    $('#alphanumeric1, #alphanumeric2, #alphanumeric3, #alphanumeric4, #alphanumeric5').autotab_filter({ format: 'alphanumeric', uppercase: true });
    $('#regex').autotab_filter({ format: 'custom', pattern: '[^0-9\.]' });
});

/* toggle */
$(document).ready(function () {

    $('#toggle-view li').click(function () {

        var text = $(this).children('div.panel');

        if (text.is(':hidden')) {
            text.slideDown('200');
            $(this).children('span').html('-');
        } else {
            text.slideUp('200');
            $(this).children('span').html('+');
        }

    });

});
/* tables */
$(document).ready(function () {
    $('#datatable_1').dataTable();
});
$(document).ready(function () {
    $('#datatable_2').dataTable({
        "bPaginate": false,
        "bLengthChange": false,
        "bFilter": true,
        "bSort": false,
        "bInfo": false,
        "bAutoWidth": false
    });
});
$(document).ready(function () {
    $('#datatable_3').dataTable({
        "sPaginationType": "full_numbers"
    });
});
$(document).ready(function () {
    $('#datatable_4').dataTable({
        "sScrollX": "100%",
        "sScrollXInner": "145%",
        "bScrollCollapse": true
    });
});
$(document).ready(function () {
    $('#datatable_5').dataTable({
        "sScrollY": "200px",
        "bPaginate": false,
        "bScrollCollapse": true
    });
});
$(document).ready(function () {
    $('#datatable_6').dataTable({
        "sDom": 'T<"clear">lfrtip'
    });
});


//*********************   Charts   *********************//	
$(document).ready(function () {


    /* ---------- Chart with points ---------- */
    if ($("#sincos").length) {
        var sin = [], cos = [];

        for (var i = 0; i < 14; i += 0.5) {
            sin.push([i, Math.sin(i) / i]);
            cos.push([i, Math.cos(i)]);
        }

        var plot = $.plot($("#sincos"),
			   [{ data: sin, label: "sin(x)/x" }, { data: cos, label: "cos(x)" }], {
			       series: {
			           lines: {
			               show: true,
			               lineWidth: 2,
			           },
			           points: { show: true },
			           shadowSize: 2
			       },
			       grid: {
			           hoverable: true,
			           clickable: true,
			           tickColor: "#dddddd",
			           borderWidth: 0
			       },
			       yaxis: { min: -1.2, max: 1.2 },
			       colors: ["#FA5833", "#2FABE9"]
			   });

        function showTooltip(x, y, contents) {
            $('<div id="tooltip">' + contents + '</div>').css({
                position: 'absolute',
                display: 'none',
                top: y + 5,
                left: x + 5,
                border: '1px solid #fdd',
                padding: '2px',
                'background-color': '#dfeffc',
                opacity: 0.80
            }).appendTo("body").fadeIn(200);
        }

        var previousPoint = null;
        $("#sincos").bind("plothover", function (event, pos, item) {
            $("#x").text(pos.x.toFixed(2));
            $("#y").text(pos.y.toFixed(2));

            if (item) {
                if (previousPoint != item.dataIndex) {
                    previousPoint = item.dataIndex;

                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(2),
                        y = item.datapoint[1].toFixed(2);

                    showTooltip(item.pageX, item.pageY,
                                item.series.label + " of " + x + " = " + y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;
            }
        });



        $("#sincos").bind("plotclick", function (event, pos, item) {
            if (item) {
                $("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
                plot.highlight(item.series, item.datapoint);
            }
        });

    }

    /* ---------- Flot chart ---------- */
    if ($("#flotchart").length) {
        var d1 = [];
        for (var i = 0; i < Math.PI * 2; i += 0.25)
            d1.push([i, Math.sin(i)]);

        var d2 = [];
        for (var i = 0; i < Math.PI * 2; i += 0.25)
            d2.push([i, Math.cos(i)]);

        var d3 = [];
        for (var i = 0; i < Math.PI * 2; i += 0.1)
            d3.push([i, Math.tan(i)]);

        $.plot($("#flotchart"), [
			{ label: "sin(x)", data: d1 },
			{ label: "cos(x)", data: d2 },
			{ label: "tan(x)", data: d3 }
        ], {
            series: {
                lines: { show: true },
                points: { show: true }
            },
            xaxis: {
                ticks: [0, [Math.PI / 2, "\u03c0/2"], [Math.PI, "\u03c0"], [Math.PI * 3 / 2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]
            },
            yaxis: {
                ticks: 10,
                min: -2,
                max: 2
            },
            grid: {
                tickColor: "#dddddd",
                borderWidth: 0
            },
            colors: ["#FA5833", "#2FABE9", "#FABB3D"]
        });
    }

    /* ---------- Stack chart ---------- */
    if ($("#stackchart").length) {
        var d1 = [];
        for (var i = 0; i <= 10; i += 1)
            d1.push([i, parseInt(Math.random() * 30)]);

        var d2 = [];
        for (var i = 0; i <= 10; i += 1)
            d2.push([i, parseInt(Math.random() * 30)]);

        var d3 = [];
        for (var i = 0; i <= 10; i += 1)
            d3.push([i, parseInt(Math.random() * 30)]);

        var stack = 0, bars = true, lines = false, steps = false;

        function plotWithOptions() {
            $.plot($("#stackchart"), [d1, d2, d3], {
                series: {
                    stack: stack,
                    lines: { show: lines, fill: true, steps: steps },
                    bars: { show: bars, barWidth: 0.6 },
                },
                colors: ["#FA5833", "#2FABE9", "#FABB3D"]
            });
        }

        plotWithOptions();

        $(".stackControls input").click(function (e) {
            e.preventDefault();
            stack = $(this).val() == "With stacking" ? true : null;
            plotWithOptions();
        });
        $(".graphControls input").click(function (e) {
            e.preventDefault();
            bars = $(this).val().indexOf("Bars") != -1;
            lines = $(this).val().indexOf("Lines") != -1;
            steps = $(this).val().indexOf("steps") != -1;
            plotWithOptions();
        });
    }


    // USER ACTIVE
    if ($("#activeUsers").length) {
        var d1 = [];

        for (var i = 0; i <= 160; i += 1) {
            d1.push([i, parseInt(Math.random() * 123120)]);
        }

        var stack = 0, bars = true, lines = false, steps = false;

        function plotWithOptions2() {

            $.plot($("#activeUsers"), [d1], {
                series: {
                    bars: {
                        show: bars,
                        fill: true,
                        barWidth: 0.1,
                        align: "center",
                        lineWidth: 5,
                        fillColor: { colors: [{ opacity: 1 }, { opacity: 0.5 }] }
                    },
                },
                grid: {
                    hoverable: true,
                    clickable: true,
                    tickColor: "#dddddd",
                    borderWidth: 0,
                },
                colors: ["#2d8aeb"],
                xaxis: { ticks: 0, tickDecimals: 0, tickFormatter: function (v, a) { return v } },
                yaxis: { ticks: 5, tickDecimals: 0, tickFormatter: function (v) { return v } },

            });
        }

        plotWithOptions2();

    }
});



//////////////////////
/* ---------- Sparkline Charts ---------- */
$(document).ready(function () {
    $('.linecustom').sparkline('html',
			{
			    height: '26px', width: '100px', lineColor: '#4d9ced', fillColor: '#cfe6ef',
			    minSpotColor: false, maxSpotColor: false, spotColor: '#467e8c', spotRadius: 3
			});
    $(".sparkbar").sparkline('html', {
        type: 'bar',
        height: '26px',
        barColor: '#80b031'
    });
});




/* Pie charts */
$(document).ready(function () {
    if ($("#graph1").length) {
        $(function () {
            var data = [];
            var series = Math.floor(Math.random() * 10) + 1;
            for (var i = 0; i < series; i++) {
                data[i] = { label: "Series" + (i + 1), data: Math.floor(Math.random() * 100) + 1 }
            }

            $.plot($("#graph1"), data,
            {
                series: {
                    pie: {
                        show: true,
                        radius: 1,
                        label: {
                            show: true,
                            radius: 2 / 3,
                            formatter: function (label, series) {
                                return '<div style="font-size:11px;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '%</div>';
                            },
                            threshold: 0.1
                        }
                    }
                },
                legend: {
                    show: false
                },
                grid: {
                    hoverable: false,
                    clickable: true
                },
            });

            $("#interactive").bind("plothover", pieHover);
            $("#interactive").bind("plotclick", pieClick);


        });

        function pieHover(event, pos, obj) {
            if (!obj)
                return;
            percent = parseFloat(obj.series.percent).toFixed(2);
            $("#hover").html('<span style="font-weight: bold; color: ' + obj.series.color + '">' + obj.series.label + ' (' + percent + '%)</span>');
        }
        function pieClick(event, pos, obj) {
            if (!obj)
                return;
            percent = parseFloat(obj.series.percent).toFixed(2);
            alert('' + obj.series.label + ': ' + percent + '%');
        }
    }
});

/* Pie charts 2*/
$(document).ready(function () {
    if ($("#graph2").length) {
        $(function () {
            var data = [];
            var series = Math.floor(Math.random() * 10) + 1;
            for (var i = 0; i < series; i++) {
                data[i] = { label: "Series" + (i + 1), data: Math.floor(Math.random() * 100) + 1 }
            }

            $.plot($("#graph2"), data,
            {
                series: {
                    pie: {
                        show: true,
                        radius: 300,
                        label: {
                            show: true,
                            formatter: function (label, series) {
                                return '<div style="font-size:11px;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '%</div>';
                            },
                            threshold: 0.1
                        }
                    }
                },
                legend: {
                    show: false
                },
                grid: {
                    hoverable: false,
                    clickable: true
                },
            });

            $("#interactive").bind("plothover", pieHover);
            $("#interactive").bind("plotclick", pieClick);


        });

        function pieHover(event, pos, obj) {
            if (!obj)
                return;
            percent = parseFloat(obj.series.percent).toFixed(2);
            $("#hover").html('<span style="font-weight: bold; color: ' + obj.series.color + '">' + obj.series.label + ' (' + percent + '%)</span>');
        }
        function pieClick(event, pos, obj) {
            if (!obj)
                return;
            percent = parseFloat(obj.series.percent).toFixed(2);
            alert('' + obj.series.label + ': ' + percent + '%');
        }
    }
});


/* Updating graphs real-time */
$(document).ready(function () {
    if ($("#updateInterval").length) {
        $(function () {
            // we use an inline data source in the example, usually data would
            // be fetched from a server
            var data = [], totalPoints = 300;
            function getRandomData() {
                if (data.length > 0)
                    data = data.slice(1);

                // do a random walk
                while (data.length < totalPoints) {
                    var prev = data.length > 0 ? data[data.length - 1] : 50;
                    var y = prev + Math.random() * 10 - 5;
                    if (y < 0)
                        y = 0;
                    if (y > 100)
                        y = 100;
                    data.push(y);
                }

                // zip the generated y values with the x values
                var res = [];
                for (var i = 0; i < data.length; ++i)
                    res.push([i, data[i]])
                return res;
            }

            // setup control widget
            var updateInterval = 1000;
            $("#updateInterval").val(updateInterval).change(function () {
                var v = $(this).val();
                if (v && !isNaN(+v)) {
                    updateInterval = +v;
                    if (updateInterval < 1)
                        updateInterval = 1;
                    if (updateInterval > 2000)
                        updateInterval = 2000;
                    $(this).val("" + updateInterval);
                }
            });

            // setup plot
            var options = {
                series: { shadowSize: 0 }, // drawing is faster without shadows
                yaxis: { min: 0, max: 120 },
                xaxis: { show: false },

                colors: ["#2686d2"],
                series: {
                    lines: {
                        lineWidth: 1,
                        fill: true,
                        fillColor: { colors: [{ opacity: 0.5 }, { opacity: 1.0 }] },
                        steps: false,
                        show: true

                    }, points: { show: false }
                }
            };
            var plot = $.plot($(".autoUpdate"), [getRandomData()], options);

            function update() {
                plot.setData([getRandomData()]);
                // since the axes don't change, we don't need to call plot.setupGrid()
                plot.draw();

                setTimeout(update, updateInterval);
            }

            update();

        });
    }
});
